package com.example.util;

import com.example.config.HeaderConfig;
import com.example.service.LoginService;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.URL;
import java.util.Map;

/**
 * HTTP请求工具类
 * 职责：处理所有HTTP请求相关操作
 * 功能：
 * - 发送HTTP请求并获取响应
 * - 处理请求重试机制
 * - 管理请求超时
 * - 异常处理和日志记录
 */
@Component
public class HttpRequestUtil {
    
    private final HeaderConfig headerConfig;
    private final LoginService loginService;
    private boolean loginFailure = false;

    @Autowired
    public HttpRequestUtil(HeaderConfig headerConfig, LoginService loginService) {
        this.headerConfig = headerConfig;
        this.loginService = loginService;
    }

    /**
     * 获取网页文档
     * @param url 目标URL
     * @param retryCount 重试次数
     * @return Jsoup Document对象
     */
    public Document fetchDocument(String url, int retryCount) {
        for (int i = 0; i < retryCount; i++) {
            try {
                // 获取域名
                String domain = new URL(url).getHost();
                
                // 准备请求
                Connection connection = Jsoup.connect(url)
                        .headers(headerConfig.getHeaders(url))
                        .timeout(10000)
                        .ignoreContentType(true)
                        .ignoreHttpErrors(true);

                // 如果已登录，添加cookies
                if (loginService.isLoggedIn(domain)) {
                    connection.cookies(loginService.getCookies(domain));
                }

                // 发送请求
                Document doc = connection.get();
                
                // 检查是否需要登录
                if (loginService.needLogin(doc, url)) {
                    System.out.println("需要登录: " + url);
                    // 如果已经登录但仍然需要登录，说明登录已失效
                    if (loginService.isLoggedIn(domain)) {
                        System.out.println("登录已失效，尝试重新登录");
                        loginService.logout(domain);
                    }
                    
                    if (loginService.login(domain)) {
                        // 登录成功后重试
                        return fetchDocument(url, retryCount - i - 1);
                    } else {
                        System.err.println("\u001B[31m登录失败，跳过URL: " + url + "\u001B[0m");
                        loginFailure = true;
                        // 记录登录失败信息
                        loginService.recordLoginFailure(domain, url, doc, "登录失败");
                        return null;
                    }
                }

                return doc;
            } catch (Exception e) {
                System.err.println("获取页面失败 (" + (i + 1) + "/" + retryCount + "): " + url + " - " + e.getMessage());
                if (i == retryCount - 1) {
                    return null;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            }
        }
        return null;
    }

    /**
     * 检查是否是登录失败导致的页面获取失败
     * @return 是否是登录失败
     */
    public boolean isLoginFailure() {
        return loginFailure;
    }
} 